<?php

namespace App\Http\Controllers;

use App\Helpers\LogHelper;
use App\Helpers\MvcHelper;
use Exception;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Validator;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected array $params;     // 接口请求参数
    protected array $sysParams;  // 其他请求参数

    public function __construct()
    {
        /**
         * 将业务参数和系统参数放入基类的变量中
         */
        $this->params = MvcHelper::getApiRequestParams();
        $this->sysParams = MvcHelper::getRequestSysParams();
    }

    /**
     * 加载业务
     *
     * @tips service只能为对应的controller服务，
     *       暂不考虑service重名问题
     *
     * @param string $service
     *
     * @return mixed
     * @throws Exception
     */
    protected function loadService(string $service)
    {
        // service 基本名称
        $serviceName = getClassBaseName($service, 'Service');
        // controller 基本名称 get_class($this) 调用本方法的实际对象的名字
        $controllerName = getClassBaseName(get_class($this), 'Controller');
        // service基本名称 需要和controller 基本名称 一致
        if ($controllerName != $serviceName) {
            throw new Exception('can not load service');
        }

        return loadClass($service, 'App\\Services');
    }

    /**
     * 规则验证：不抛出异常
     *
     * @param $rule
     * @return bool
     */
    protected function ruleCheck($rule): bool
    {
        $validator = Validator::make($this->params, $rule);

        if (!empty($validator->errors()->first())) {
            $message = [
                $this->params,
                $validator->errors()->first(),
            ];
            LogHelper::info('Validator', $message);
        }
        return $validator->fails();
    }

    /**
     * 规则验证: 抛出异常
     *
     * @param $rule
     * @throws Exception
     */
    protected function getRuleCheck($rule)
    {
        $validator = Validator::make($this->params, $rule);

        if (!empty($validator->errors()->first())) {
            throw new Exception($validator->errors()->first(), 508);
        }
    }
}
